#include "ulog_app.h"
#include <rtthread.h>
#include <stdlib.h>
#include <ulog.h>
#include <ulog_be.h>
#include "uc_log.h"
#define DBG_ENABLE
#define DBG_TAG "file_be"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

static ulog_file_be_t s_be = {0};
 int ulog_app_init(void)
{
    ulog_file_backend_init(&s_be, ULOG_NAME, ULOG_DIR_PATH, ULOG_MAX_NUM, ULOG_MAX_SIZE, ULOG_BUF_SIZE);
    if (ulog_trim_file(&s_be))
    {
        return -RT_ERROR;
    }
    ulog_find_file(&s_be, ULOG_DIR_PATH, ULOG_TMP_NAME, 1);
    return RT_EOK;
}
INIT_APP_EXPORT(ulog_app_init);

void ulog_app_enable(char enable)
{
    if (RT_TRUE == enable)
    {
        ulog_file_backend_enable(&s_be);
    }
    else
    {
        ulog_file_backend_disable(&s_be);
    }
}

char ulog_app_is_enable(void)
{
    return s_be.enable ? RT_TRUE : RT_FALSE;
}

// 函数用于生成随机字符
static char random_char() 
{
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    int key = rand() % (sizeof(charset) - 1);
    return charset[key];
}

#ifdef FINSH_USING_MSH
#include <finsh.h>
static int cmd_ulog_en(int argc, char **argv)
{
    int i = 0, j = 0;
    int out_cnt = 1;
    char *test_str = RT_NULL;
    if (argc < 2)
    {
        rt_kprintf("Usage:./ulog_en 0/1/q \r\n");
        return -1;
    }
    switch (argv[1][0])
    {
    case 'q':
        rt_kprintf("ulog %s \r\n", ulog_app_is_enable() ? "enabled" : "disabled");
        break;
    case '0':
    case '1':
        ulog_app_enable(argv[1][0] - '0');
        break;
    case 't':
        if (!ulog_app_is_enable()) break;
        if (3 == argc) out_cnt = argv[2][0] - '0';
        test_str = rt_calloc(1, ULOG_BUF_SIZE);
        for (i = 0; i < out_cnt; i++)
        {
            for (j = 0; j < ULOG_BUF_SIZE; j++)
            {
                test_str[j] = random_char();
            }
            test_str[ULOG_BUF_SIZE - 1] = '\0';
            TRACE_I("%s", test_str);
        }
        rt_free(test_str);
        break;
    default:
        rt_kprintf("ulog_en unknow the parameter (%c) \r\n", argv[1][0]);
        rt_kprintf("Usage:./ulog_en 0/1/q \r\n");
        break;
    }
    return RT_EOK;
}
MSH_CMD_EXPORT_ALIAS(cmd_ulog_en, ulog_en, ulog enabled by 1 others are disabled);
#endif

